<?php

namespace App\Jobs\OpenShop;

use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Service\OpenShop\Feishu\MessageSendService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class ChangeManagerJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 1800;

    private array $address;
    private int   $operateUid;
    private int   $type;
    private array $userMapShopIds;
    private array $delUserIds;

    private int $totalNum = 0;
    private array $mainProcessIds = [];

    /**
     * 更换门店的顾问
     *
     * @param int $type 类型
     * @param array $address 省市区
     * @param int $operateUid 操作人
     * @param array $userMapShopIds 用户关联门店信息
     * @param array $delUserIds 被删除督导用户数据
     */
    public function __construct(int $type, array $address, int $operateUid, array $userMapShopIds = [], array $delUserIds = [])
    {
        $this->address        = $address;
        $this->operateUid     = $operateUid;
        $this->type           = $type;
        $this->userMapShopIds = $userMapShopIds;
        $this->delUserIds     = $delUserIds;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $uuid = Str::uuid()->toString();

        Log::info("ChangeManager Queue debug...{$uuid}", [$this->type, $this->operateUid, $this->address, $this->userMapShopIds]);

        $userIds  = array_column($this->userMapShopIds, 'userId');
        $getUsers = collect(RmsUserService::getRmsUserInfoByUserIds(array_merge($userIds, [$this->operateUid]), [], true)['data'] ?? [])->keyBy('id')->toArray();

        $operateUserName     = $getUsers[$this->operateUid]['username'] ?? '';
        $operateUserFeishuId = $getUsers[$this->operateUid]['feishuUserId'] ?? '';

        if ($this->type == OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER) {

            // 根据门店id关联督导
            if ($this->userMapShopIds) {
                foreach ($this->userMapShopIds as $v) {

                    $targetUid      = $v['userId'];
                    $targetUserName = $getUsers[$v['userId']]['username'] ?? '';

                    $mainProcessIds = OpenShopMainProcessModel::query()->whereIn('shopId', $v['shopIds'])->pluck('id');

                    // 更换督导
                    OpenShopOrderManagerModel::query()
                        ->whereIn('mainProcessId', $mainProcessIds)
                        ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)
                        ->get()
                        ->each(
                            function ($item) use ($targetUserName, $operateUserName, $targetUid) {
                                $userInfo = (object)[
                                    'id'       => $this->operateUid,
                                    'username' => $operateUserName,
                                ];
                                $paramsFormat = (object)[
                                    'id'          => $item->id,
                                    'type'        => $item->type,
                                    'managerId'   => $targetUid,
                                    'managerName' => $targetUserName,
                                    'shopId'      => $item->shopId,
                                ];

                                Log::info("ChangeManager Queue start... targetUid:{$targetUid} operateUid:{$this->operateUid} id:{$item->id}");

                                try {
                                    $do = OrderService::changeManager($userInfo, $paramsFormat, true);
                                    if ($do) {
                                        $this->totalNum++;
                                        $this->mainProcessIds[] = $item->mainProcessId;
                                    }
                                } catch (\Exception $e) {
                                    Log::warning($e);
                                }

                                Log::info("ChangeManager Queue end...id:{$item->id}");
                            }
                        );
                }

                foreach ($this->userMapShopIds as $v) {

                    $mainProcessIds = OpenShopMainProcessModel::query()->whereIn('shopId', $v['shopIds'])->pluck('id');

                    // 更换督导--当前用户不关联门店的数据
                    OpenShopOrderManagerModel::query()
                        ->where('managerUid', $v['userId'])
                        ->whereNotIn('mainProcessId', $mainProcessIds)
                        ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)
                        ->get()
                        ->each(
                            function ($item) use ($operateUserName) {
                                $userInfo = (object)[
                                    'id'       => $this->operateUid,
                                    'username' => $operateUserName,
                                ];
                                $paramsFormat = (object)[
                                    'id'          => $item->id,
                                    'type'        => $item->type,
                                    'managerId'   => 0,
                                    'managerName' => '',
                                    'shopId'      => $item->shopId,
                                ];

                                Log::info("ChangeManager2 Queue start... targetUid:0 operateUid:{$this->operateUid} id:{$item->id}");

                                try {
                                    $do = OrderService::changeManager($userInfo, $paramsFormat, true, true);
                                    if ($do) {
                                        $this->totalNum++;
                                        $this->mainProcessIds[] = $item->mainProcessId;
                                    }
                                } catch (\Exception $e) {
                                    Log::warning($e);
                                }

                                Log::info("ChangeManager2 Queue end...id:{$item->id}");
                            }
                        );
                }
            }

            // 被删除督导用户数据
            if ($this->delUserIds) {
                foreach ($this->delUserIds as $v) {

                    // 删除督导
                    OpenShopOrderManagerModel::query()
                        ->where('managerUid', $v)
                        ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)
                        ->get()
                        ->each(
                            function ($item) use ($v, $operateUserName) {
                                $userInfo     = (object)[
                                    'id'       => $this->operateUid,
                                    'username' => $operateUserName,
                                ];
                                $paramsFormat = (object)[
                                    'id'          => $item->id,
                                    'type'        => $item->type,
                                    'managerId'   => 0,
                                    'managerName' => '',
                                    'shopId'      => $item->shopId,
                                ];

                                Log::info("delManager Queue start... targetUid:{$v} operateUid:{$this->operateUid} id:{$item->id}");

                                try {
                                    $do = OrderService::changeManager($userInfo, $paramsFormat, true, true);
                                    if ($do) {
                                        $this->totalNum++;
                                        $this->mainProcessIds[] = $item->mainProcessId;
                                    }
                                } catch (\Exception $e) {
                                    Log::warning($e);
                                }

                                Log::info("delManager Queue end...id:{$item->id}");
                            }
                        );

                }
            }


            /* 原来是按照区域查询订单进行处理的
             * foreach ($this->address as $address) {
                $orderNos = OpenShopAddressModel::query()
                                                ->where('provinceCode', $address['provinceCode'])
                                                ->when($address['cityCode'] ?? '', function ($query) use ($address) {
                                                    $query->where('cityCode', $address['cityCode']);
                                                })
                                                ->when($address['regionCode'] ?? '', function ($query) use ($address) {
                                                    $query->where('areaCode', $address['regionCode']);
                                                })
                                                ->pluck('orderNo')
                                                ->toArray();

                Log::info("ChangeManager Queue orderNos...{$uuid}", $orderNos);

                $mainProcessIds = OpenShopMainProcessModel::query()->whereIn('orderNo', $orderNos)->pluck('id');

                $targetUid       = $address['targetUid'];
                $targetUserName  = RmsUserService::getRmsUserInfoByUserIds([$targetUid], [],
                        true)['data'][0]['username'] ?? '';

                // 更换督导
                OpenShopOrderManagerModel::query()
                                         ->whereIn('mainProcessId', $mainProcessIds)
                                         ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)
                                         ->where('managerUid', '!=', $targetUid)
                                         ->get()
                                         ->each(function ($item) use ($targetUserName, $operateUserName, $targetUid) {
                                             $userInfo     = (object)[
                                                 'id'       => $this->operateUid,
                                                 'username' => $operateUserName,
                                             ];
                                             $paramsFormat = (object)[
                                                 'id'          => $item->id,
                                                 'type'        => $item->type,
                                                 'managerId'   => $targetUid,
                                                 'managerName' => $targetUserName,
                                             ];

                                             Log::info("ChangeManager Queue start... targetUid:{$targetUid} operateUid:{$this->operateUid} id:{$item->id}");

                                             try {
                                                 $do = OrderService::changeManager($userInfo, $paramsFormat, true, true);
                                                 if ($do) {
                                                     $this->totalNum++;
                                                     $this->mainProcessIds[] = $item->mainProcessId;
                                                 }
                                             } catch (\Exception $e) {
                                                 Log::warning($e);
                                             }

                                             Log::info("ChangeManager Queue end...id:{$item->id}");
                                         });
            }*/

            $orderNoStr = OpenShopMainProcessModel::query()->whereIn('id', $this->mainProcessIds)->pluck('orderNo')->implode('\n');

            // 简单飞书推送，督导更换完毕
            $templateJson = vsprintf(file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/changeManager.json')), ['营运', $this->totalNum, $operateUserName, $orderNoStr]);
            Log::info($templateJson);

            MessageSendService::sendMessage($operateUserFeishuId, 'user_id', json_decode($templateJson, true), 'interactive', UserPermissionAuth::MODULE_OPEN_SHOP);
        }

        Log::info("ChangeManager Queue end...{$uuid}");
    }
}
